#include "SharedVariables.fxh"

float4x4 World;

texture SpecularMap;
sampler specularSampler = sampler_state
{
    Texture = (SpecularMap);
    MAGFILTER = LINEAR;
    MINFILTER = LINEAR;
    MIPFILTER = LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

texture NormalMap;
sampler normalSampler = sampler_state
{
    Texture = (NormalMap);
    MAGFILTER = LINEAR;
    MINFILTER = LINEAR;
    MIPFILTER = LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

texture Texture;
sampler diffuseSampler = sampler_state
{
    Texture = (Texture);
    MAGFILTER = LINEAR;
    MINFILTER = LINEAR;
    MIPFILTER = LINEAR;
    AddressU = Wrap;
    AddressV = Wrap;
};

float specularIntensity = 0.8f;
float specularPower = 0.5f; 

struct ObjectVSInput
{
    float4 Position : POSITION0;
    float3 Normal : NORMAL0;
    float2 TexCoord : TEXCOORD0;
    float3 Binormal : BINORMAL0;
    float3 Tangent : TANGENT0;
};

struct ObjectVSOutput
{
    float4 Position : POSITION0;
	float2 TexCoord : TEXCOORD0;
	float2 Depth : TEXCOORD1;
	float3x3 tangentToWorld : TEXCOORD2;
};

struct ObjectPSOutput
{
	float4 Diffuse : COLOR0;
	float4 Depth : COLOR1;
	float4 Normal : COLOR2;
};

ObjectVSOutput DrawObjectVS(ObjectVSInput input)
{
    ObjectVSOutput output;

    float4 pos = mul(input.Position, World);
    output.Position = mul(pos, ViewProj);
    output.Depth.x = output.Position.z;
	output.Depth.y = output.Position.w;
	output.TexCoord = input.TexCoord;
	
	output.tangentToWorld[0] = mul(input.Tangent, World);
	output.tangentToWorld[1] = mul(input.Binormal, World);
	output.tangentToWorld[2] = mul(input.Normal, World);

    return output;
}

ObjectPSOutput DrawObjectPS(ObjectVSOutput input)
{
	ObjectPSOutput output;
	float4 diffuseAttributes = tex2D(diffuseSampler, input.TexCoord);
	float4 specularAttributes = tex2D(specularSampler, input.TexCoord);
	float4 normalAttributes = tex2D(normalSampler, input.TexCoord);
	
	output.Depth = input.Depth.x / input.Depth.y;
	output.Diffuse.rgb = diffuseAttributes.rgb;
	output.Diffuse.a = specularAttributes.r;
	float3 normalFromMap = normalAttributes.rgb;
	normalFromMap = 2.0f * normalFromMap - 1.0f;
	normalFromMap = normalize(mul(normalFromMap, input.tangentToWorld));
	output.Normal.rgb = 0.5f * (normalFromMap + 1.0f);
	output.Normal.a = specularAttributes.a;
    return output;
}

technique DrawObject
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 DrawObjectVS();
        PixelShader = compile ps_2_0 DrawObjectPS();
    }
}